package com.eaero.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eaero.CommonResp;
import com.eaero.entity.TraceUser;
import com.eaero.entity.TraceWorkOrder;
import com.eaero.mapper.TraceWorkOrderMapper;
import com.eaero.service.ITraceUserService;
import com.eaero.service.ITraceWorkOrderService;
import com.eaero.service.workorder.pojo.CancelWorkOrderRequest;
import com.eaero.service.workorder.pojo.WorkOrderNoRequest;
import com.eaero.service.workorder.pojo.WorkOrderRequest;
import com.eaero.service.workorder.pojo.WorkOrderResultVo;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zb
 * @since 2023-03-14
 */
@Service
public class TraceWorkOrderServiceImpl extends ServiceImpl<TraceWorkOrderMapper, TraceWorkOrder> implements ITraceWorkOrderService {

    private Gson gson = new Gson();
    @Autowired
    private ITraceUserService traceUserService;

    @Override
    public void genWorkOrder() {
        ArrayList<String> stsStrList = Lists.newArrayList("N", "R", "D", "P", "U");
        ArrayList<TraceWorkOrder> list = Lists.newArrayList();
        for (int i = 0; i < 5; i++) {
            TraceWorkOrder traceWorkOrder = new TraceWorkOrder();
            traceWorkOrder.setId(RandomStringUtils.randomAlphanumeric(32));
            traceWorkOrder.setReqNo(StrUtil.format("XA{}", RandomUtil.randomNumbers(8)));
            traceWorkOrder.setCrtDate(LocalDateTime.now());
            traceWorkOrder.setReqUserCode("user001");
            traceWorkOrder.setReqUserName("傅詩涵");
            traceWorkOrder.setUptDate(null);
            traceWorkOrder.setUptBy(null);
            traceWorkOrder.setUptUserCode(null);
            traceWorkOrder.setReqUserName(null);
            traceWorkOrder.setTailNo(StrUtil.format("BS-{}", RandomUtil.randomNumbers(4)));
            traceWorkOrder.setVisitDesc(StrUtil.format("C{}", RandomUtil.randomNumbers(1)));
            traceWorkOrder.setReqSts(stsStrList.get(i));
            traceWorkOrder.setRemark(StrUtil.format("备注{}", RandomStringUtils.randomAlphanumeric(8)));
            traceWorkOrder.setOrigin("P");
            list.add(traceWorkOrder);
        }
        this.saveBatch(list);
    }

    @Override
    public CommonResp getWorkOrder(WorkOrderRequest workOrderRequest) {

        if (ObjectUtil.isEmpty(workOrderRequest)) {
            return CommonResp.buildFailMsg("必须至少传一个参数");
        }

        LocalDateTime crtStartTime = null;
        LocalDateTime crtEndTime = null;
        if (StrUtil.isNotBlank(workOrderRequest.getCrtDate())) {
            LocalDate crtDate = LocalDate.parse(workOrderRequest.getCrtDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            crtStartTime = LocalDateTime.of(crtDate, LocalTime.MIN);
            crtEndTime = LocalDateTime.of(crtDate, LocalTime.MAX);
        }
        LocalDateTime sndStartTime = null;
        LocalDateTime sndEndTime = null;
        if (StrUtil.isNotBlank(workOrderRequest.getSndDate())) {
            LocalDate sndDate = LocalDate.parse(workOrderRequest.getSndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            sndStartTime = LocalDateTime.of(sndDate, LocalTime.MIN);
            sndEndTime = LocalDateTime.of(sndDate, LocalTime.MAX);
        }
        List<TraceWorkOrder> workOrderList = this.list(Wrappers.<TraceWorkOrder>lambdaQuery()
                .like(StrUtil.isNotBlank(workOrderRequest.getReqNo()), TraceWorkOrder::getReqNo, workOrderRequest.getReqNo())
                .like(StrUtil.isNotBlank(workOrderRequest.getReqBy()), TraceWorkOrder::getReqUserName, workOrderRequest.getReqBy())
                .ge(ObjectUtil.isNotEmpty(crtStartTime), TraceWorkOrder::getCrtDate, crtStartTime)
                .le(ObjectUtil.isNotEmpty(crtEndTime), TraceWorkOrder::getCrtDate, crtEndTime)
                .eq(StrUtil.isNotBlank(workOrderRequest.getReqSts()), TraceWorkOrder::getReqSts, workOrderRequest.getReqSts())
                .like(StrUtil.isNotBlank(workOrderRequest.getSndBy()), TraceWorkOrder::getReqUserName, workOrderRequest.getSndBy())
                .ge(ObjectUtil.isNotEmpty(sndStartTime), TraceWorkOrder::getCrtDate, sndStartTime)
                .le(ObjectUtil.isNotEmpty(sndEndTime), TraceWorkOrder::getCrtDate, sndEndTime)
                .eq(StrUtil.isNotBlank(workOrderRequest.getOrigin()), TraceWorkOrder::getOrigin, workOrderRequest.getOrigin()));
        if (CollUtil.isEmpty(workOrderList)) {
            return CommonResp.buildFailMsg("暂无申请单");
        }
        List<WorkOrderResultVo> respList = workOrderList.stream().map(traceWorkOrder -> {
            WorkOrderResultVo resultVo = new WorkOrderResultVo();
            BeanUtil.copyProperties(traceWorkOrder, resultVo);
            resultVo.setReqBy(StrUtil.format("{} {}", traceWorkOrder.getReqUserCode(), traceWorkOrder.getReqUserName()));
            if (StrUtil.isNotBlank(traceWorkOrder.getUptUserCode()) && StrUtil.isNotBlank(traceWorkOrder.getUptUserName())) {
                resultVo.setUptBy(StrUtil.format("{} {}", traceWorkOrder.getUptUserCode(), traceWorkOrder.getReqUserName()));
            }
            if (ObjectUtil.isNotEmpty(traceWorkOrder.getCrtDate())) {
                resultVo.setCrtDate(DateUtil.format(traceWorkOrder.getCrtDate(), "yyyy-MM-dd HH:mm:ss"));
            }
            if (ObjectUtil.isNotEmpty(traceWorkOrder.getUptDate())) {
                resultVo.setUptDate(DateUtil.format(traceWorkOrder.getUptDate(), "yyyy-MM-dd HH:mm:ss"));
            }
            return resultVo;
        }).collect(Collectors.toList());
        return CommonResp.buildSucsDataListMsg(respList, "数据获取成功");
    }

    @Override
    public CommonResp cancellationWorkOrder(CancelWorkOrderRequest request) {
        if (StrUtil.isBlank(request.getUserCode())) {
            return CommonResp.buildFailMsg("员工号不能为空");
        }
        boolean flag = false;
        for (WorkOrderNoRequest workOrderNoRequest : request.getCancelReq()) {
            if (StrUtil.isBlank(workOrderNoRequest.getReqNo())) {
                flag = true;
            }
        }
        if (flag) {
            return CommonResp.buildFailMsg("申请单号不能为空");
        }
        List<String> reqNos = request.getCancelReq().stream().map(WorkOrderNoRequest::getReqNo).collect(Collectors.toList());
        List<TraceWorkOrder> workOrderList = this.list(Wrappers.<TraceWorkOrder>lambdaQuery()
                .in(TraceWorkOrder::getReqNo, reqNos));
        if (CollUtil.isEmpty(workOrderList)) {
            return CommonResp.buildFailMsg("作废失败");
        }
        TraceUser traceUser = traceUserService.getOne(Wrappers.<TraceUser>lambdaQuery().eq(TraceUser::getUserCode, request.getUserCode()));
        workOrderList.forEach(traceWorkOrder -> {
            traceWorkOrder.setReqSts("D");
            traceWorkOrder.setUptUserCode(traceUser.getUserCode());
            traceWorkOrder.setUptUserName(traceUser.getUserName());
            traceWorkOrder.setUptDate(LocalDateTime.now());
        });
        this.updateBatchById(workOrderList);
        return CommonResp.buildSucsDataListMsg(null, "作废成功");
    }
}
